package com.namuan.jp_stock.activity;



import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.namuan.jp_stock.activity.UserProfileActivity.LoadActivityRequestListener;
import com.namuan.jp_stock.object.ShotActivity;
import com.namuan.jp_stock.util.ActivityItemAdapter;
import com.namuan.jp_stock.util.AsyncJustplaceRunner;
import com.namuan.jp_stock.util.BaseRequestListener;
import com.namuan.jp_stock.util.ImageManager;
import com.namuan.jp_stock.util.Justplace;
import com.namuan.jp_stock.util.JustplaceError;
import com.namuan.jp_stock.util.ObjUtils;
import com.namuan.jp_stock.util.PointImageView;
import com.namuan.jp_stock.util.SessionStore;
import com.namuan.jp_stock.util.Util;
import com.namuan.jp_stock.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyProfileActivity extends Activity implements OnClickListener,
OnItemClickListener, RadioGroup.OnCheckedChangeListener {

	
	private Activity mActivity;

	private ArrayList<ShotActivity> activityItems;
	
	private ListView activityListView;
	private ActivityItemAdapter aa;
	
	private TextView tvHasItem;
	private Justplace mJustplace;
	private AsyncJustplaceRunner mAsyncRunner;
	private ImageButton imgBtnAddFriend;
	private ImageView navBtn1;
	private ImageView navBtn2;
	private ImageView navBtn3;
	private ImageView navBtn4;
	private PointImageView userImg;
	private TextView userRankingText;
	private TextView userExpText;
	private TextView userProfileBioText;
	private TextView userProfileNickText;
	private String userRanking;
	private String userExp;
	private String userMayor;
	private String strUserImg;
	private String strFacebook;
	private String strTwitter;
	private String userBio;
	private String usernickname;
	
	
	private String usernick;
	private String loginnick;
	private boolean IsAllReadUserInfo;//동기처리하기 위해서

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.userprofile);
		LoginActivity.activityList.add(this);
		
		IsAllReadUserInfo = false;
		mActivity = this;
		/* 구분해줘야 되나??
		// 1. activity view 페이지에서 넘어온 경우
		userid = this.getIntent().getExtras().getString("activityUseridStr");
		// 2. justedList view 페이지에서 넘어온 경우
		if(userid == null)
			userid = this.getIntent().getExtras().getString("justedUseridStr");*/
		ImageButton headerWriteBtn = (ImageButton) findViewById(R.id.headerWriteBtn);
		TextView userHeaderNickname = (TextView) findViewById(R.id.userHeaderNickname);
		
		activityListView = (ListView) findViewById(R.id.activityListView);
		tvHasItem = (TextView) findViewById(R.id.tvHasItem);
		imgBtnAddFriend = (ImageButton) findViewById(R.id.imgBtnAddFriend);
		imgBtnAddFriend.setOnClickListener(this);
		
		userRankingText = (TextView) findViewById(R.id.userRankingText);
		userExpText = (TextView) findViewById(R.id.userExpText);
		
		navBtn1 = (ImageView) findViewById(R.id.navBtn1);
		navBtn2 = (ImageView) findViewById(R.id.navBtn2);
		navBtn3 = (ImageView) findViewById(R.id.navBtn3);
		navBtn4 = (ImageView) findViewById(R.id.navBtn4);


		navBtn2.setImageResource(R.drawable.stockline_nor);
		navBtn3.setImageResource(R.drawable.friendsline_nor);
		navBtn4.setImageResource(R.drawable.profile_nor);
		
		headerWriteBtn.setOnClickListener(this);

		userImg = (PointImageView) findViewById(R.id.userImg);

		userProfileBioText = (TextView) findViewById(R.id.userProfileBioText);
		userProfileNickText = (TextView) findViewById(R.id.userProfileNickText);

		userHeaderNickname.setOnClickListener(this);
		navBtn1.setOnClickListener(this);
		navBtn2.setOnClickListener(this);
		navBtn3.setOnClickListener(this);
		navBtn4.setOnClickListener(this);

		
		headerWriteBtn.setOnClickListener(this);
		
		
		activityItems = new ArrayList<ShotActivity>();
		aa = new ActivityItemAdapter(this, R.layout.activity_list_row,
				activityItems);
		
		
		mJustplace = new Justplace();
		SessionStore.restore(mJustplace, this);
		mJustplace.setHeader(userHeaderNickname);
		mAsyncRunner = new AsyncJustplaceRunner(mJustplace);
		init();
	}
	
	
	private void init() {

		Bundle params = new Bundle();
		loginnick = mJustplace.getmUserNickname();
		
		Bundle userparams = new Bundle();
		userparams.putString("mynick", "");
		userparams.putString("usernick", loginnick);
		mAsyncRunner.request("userscore.do", userparams, "POST",
				new LoadUserScoreRequestListener(), null);
		
		while(IsAllReadUserInfo = false){
			
		}
		Bundle ShotListparams = new Bundle();
		ShotListparams.putString("usernickname", loginnick);
		mAsyncRunner.request("loaduseractivity.do", ShotListparams, "POST",
				new LoadActivityRequestListener(), null);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// get Tweets ��ư Ŭ��
		case R.id.headerWriteBtn:
			Intent Insert_intent = new Intent(this, AddActivity.class);
			this.startActivity(Insert_intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;

		case R.id.usernicknameText:
			Intent userHeaderNickintent = new Intent(this,
					UserProfileActivity.class);
			this.startActivity(userHeaderNickintent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
			
		case R.id.navBtn1:// timeline
			// Intent navBtn2intent = new Intent(this, SearchActivity.class);
			Intent navBtn1intent = new Intent(this, MainActivity.class);
			navBtn1intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			this.startActivity(navBtn1intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
			break;

		case R.id.navBtn2:// stockline
			// Intent navBtn2intent = new Intent(this, SearchActivity.class);
			//Intent navBtn2intent = new Intent(this, SearchActivity.class);
			// navBtn2intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
			// Intent.FLAG_ACTIVITY_SINGLE_TOP);
			//this.startActivity(navBtn2intent);
			//overridePendingTransition(R.anim.fade, R.anim.hold);
			// finish();
			break;

		case R.id.navBtn3:// friendsline
			break;

		case R.id.navBtn4:// profile
			break;

		}
	}

// 안 쓰는 기능
	@Override
	public void onCheckedChanged(RadioGroup arg0, int arg1) {
	
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}


	

	public class LoadActivityRequestListener extends BaseRequestListener {
		public void onComplete(final String response, final Object state) {
			Log.d("StockSNS-LoadActivity", "Response: " + response.toString());
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					aa.clear();
					Log.d("StockSNS-LoadActivity",
							"Response: " + response.toString());
					try {
						JSONObject json = Util.parseJson(response);
						if (!json.getString("state").equals("false")) {
							final ArrayList<ShotActivity> shotactivitys = ObjUtils.jsonToShotActivityList(json.getJSONArray("activityList"));
							for (ShotActivity act : shotactivitys) {
								// activityItems.add(act);
								aa.add(act);
							}
							tvHasItem.setVisibility(View.GONE);
							activityListView.setAdapter(aa);
							aa.notifyDataSetChanged();
						} else {
							activityListView.setAdapter(aa);
							aa.notifyDataSetChanged();
							tvHasItem.setVisibility(View.VISIBLE);
							tvHasItem.setText(usernick + " 님이 작성한 액티비티가 없습니다.");
						}

					} catch (JSONException e) {
						Log.w("StockSNS-LoadActivity",
								"JSON Error in response");
					} catch (JustplaceError e) {
						Log.w("StockSNS-LoadActivity",
								"StockSNS Error: " + e.getMessage());
					}
				}
			});

		}
	}

	public class LoadUserScoreRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			Log.d("StockSNS-LoadUserScore", "Response: " + response.toString());
			try {
				activityItems.clear();
				Log.d("StockSNS-LoadUserScore",
						"Response: " + response.toString());
				JSONObject jsons = Util.parseJson(response);
				JSONObject json = jsons.getJSONObject("userProfile");
				
				
				Log.d("@@@@@@!!@@", json.get("ranking").toString());
				userRanking = json.get("ranking").toString();
				userExp = json.get("score").toString();
				strUserImg = json.get("profilepic").toString();
				strFacebook = json.get("facebook").toString();
				strTwitter = json.get("twitter").toString();
				userBio = json.get("bio").toString();
				usernickname = json.get("usernick").toString();
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						userRankingText.setText(Html
								.fromHtml("<font color='#000000'><b>"
										+ userRanking
										+ "</b></font><br>Ranking"));
						userExpText.setText(Html
								.fromHtml("<font color='#000000'><b>" + userExp
										+ "</b></font><br>Experience"));
						userProfileBioText.setText(userBio);
						userProfileNickText.setText(usernickname);
						//CustomImageManager customImageManager = new CustomImageManager(
						//		mActivity.getApplicationContext(),
						//		R.drawable.defaultuser);
						ImageManager imageManager = new ImageManager(mActivity.getApplicationContext(),
								R.drawable.defaultuser);
						if (strUserImg != null && !strUserImg.equals("null")) {
							userImg.setTag(Justplace.PROFILEIMG_URL + strUserImg);
							//customImageManager.displayPointImage(Justplace.TEST_URL + strUserImg, mActivity, activityUserImg);
							imageManager.displayImage(Justplace.PROFILEIMG_URL + strUserImg, mActivity, userImg);

						} else {
							userImg.setTag(null);
							//customImageManager.displayPointImage(userImg, mActivity,
							//		activityUserImg);
							imageManager.displayImage(strUserImg, mActivity, userImg);
						}
						IsAllReadUserInfo = true;
					}

				});
				
			} catch (JSONException e) {
				Log.w("StockSNS-LoadUserScore", "JSON Error in response");
				IsAllReadUserInfo = true;
			} catch (JustplaceError e) {
				Log.w("StockSNS-LoadUserScore",
						"Justplace Error: " + e.getMessage());
				IsAllReadUserInfo = true;
			}
		}
	}
	
}
